#define _GNU_SOURCE
#include <dlfcn.h> //需要编译适用 -ldl

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

#include <string.h>
#define MYFILENAME "text.txt"

// hook一般放在前面
// 定义原始函数一样类型
typedef ssize_t (*read_t)(int fd, void *buf, size_t len);
read_t read_f;

typedef ssize_t (*write_t)(int fd, const void *buf, size_t len);
write_t write_f;

// 实现原始接口，可以修改和增加代码
ssize_t read(int fd, void *buf, size_t len)
{
    int ret = read_f(fd, buf, len);
    printf("read over,buffer:%s\n", buf);
    return ret;
}

ssize_t write(int fd, const void *buf, size_t len)
{
    printf("write start,buffer:%s\n", buf);
    return write_f(fd, buf, len);
}

// 初始化
void init_hook(void)
{
    if (!read_f)
    {
        read_f = dlsym(RTLD_NEXT, "read");
    }

    if (!write_f)
    {
        write_f = dlsym(RTLD_NEXT, "write");
    }
}

int main()
{
    init_hook();
    int wfd = open(MYFILENAME, O_CREAT | O_RDWR, 0666);
    int rfd = open(MYFILENAME, O_RDONLY);

    if (wfd < 0)
        return -1;

    char *str = "Hello World!";
    write(wfd, str, strlen(str));

    char buffer[128] = {0};
    read(rfd, buffer, sizeof(buffer) - 1);

    return 0;
}
